/* Copyright © Worklight Ltd. 2006-2011.  All rights reserved. */

package com.worklight.wlclient;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

/**
 * Global utilities for WLClient API
 */
public class WLClientUtils {

	private static final String LOG_CAT = "WLClientAPI";

	/**
	 * Convert InputStream data to String
	 * @param is - The InputStream object to be converted
	 * @return The converted string
	 */
	public static String convertStreamToString(InputStream is) {
		BufferedReader reader = new BufferedReader(new InputStreamReader(is));
		StringBuilder sb = new StringBuilder();

		String line = null;
		try {
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
		} catch (IOException e) {
			throw new RuntimeException("Error reding input stream (" + is + ").", e);
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				throw new RuntimeException("Error closing input stream (" + is + ")", e);
			}
		}
		return sb.toString();
	}
	
	/**
	 * Convert JSON string to JSONObject
	 * @param jsonString - The JSON String to be converted.
	 * @return the converted JSON object.
	 * @throws JSONException - in case convert fails.
	 */
	public static JSONObject convertStringToJSON(String jsonString) throws JSONException {
		String secureJSONString = jsonString.substring(jsonString.indexOf("{"), jsonString.lastIndexOf("}") + 1);
		JSONObject jsonObject = new JSONObject(secureJSONString);
		return jsonObject;
	}

	/**
	 * Convert JSONArray to List<String>
	 * @param jsonArray
	 * @return - the converted  List<String>
	 */
	public static List<String> convertJSONArrayToList(JSONArray jsonArray){
		List <String>listToReturn = new ArrayList<String>();
		for (int i=0; i < jsonArray.length(); i++) {
			try {
				listToReturn.add((String)jsonArray.get(i));
			} catch (JSONException e) {
				throw new RuntimeException (e);
			}
		}
		return listToReturn;
	}

	public static void debug(String msg){
		Log.d(LOG_CAT, msg);
	}

	public static void error(String msg){
		Log.e(LOG_CAT, msg);
	}	

	public static void debug(String msg, Throwable throwable){
		Log.d(LOG_CAT, msg, throwable);
	}

	public static void error(String msg, Throwable throwable){
		Log.e(LOG_CAT, msg, throwable);
	}


}
